package com.weixin.program.controller;

import com.weixin.program.config.WeixinProperties;
import com.weixin.program.po.Record;
import com.weixin.program.ro.ExcelBody;
import com.weixin.program.ro.UserData;
import com.weixin.program.service.RecordService;
import com.weixin.program.utils.EmailUtil;
import com.weixin.program.utils.ExcelUtil;
import com.weixin.program.utils.WeixinUtil;
import com.weixin.program.vo.ExcelData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年03⽉05⽇<br/>
 * @version：v1.0.0<br>
 */
@Slf4j
@RestController
@RequestMapping({"/api/program/v1"})
public class SendEmailController {

    @Autowired
    RecordService recordService;

    @Autowired
    WeixinProperties properties;


    @PostMapping({"/sendEmail"})
    public Object sendEmail(@RequestBody ExcelBody excelBody, HttpServletResponse servletResponse) throws Exception {
        log.info("接收到发送邮件请求消息,excelBody={}", excelBody.toString());
        List<Record> records = recordService.selectInSectionTime(excelBody.getStartTime(), excelBody.getEndTime(), excelBody.getTouserid());
        String touserid = excelBody.getTouserid();
        String token = WeixinUtil.getToken(properties.getAppid(), properties.getAppsecret());
        UserData userData = WeixinUtil.getUserData(touserid, token);
        String nickName = userData.getNickName();
        String gender = userData.getSex() == 1 ? "先生" : "女士";
        List<ExcelData> excelDatas = new ArrayList<>(records.size());
        records.stream().forEach(record -> {
            ExcelData excelData = new ExcelData();
            BeanUtils.copyProperties(record, excelData);
            excelData.setNickName(nickName);
            String status = record.getStatus() == 1 ? "已打卡" : "未打卡";
            excelData.setStatus(status);
            excelDatas.add(excelData);
        });
        String sheetName = excelBody.getSheetName();
        String emailId = properties.getEmailId();
        String excelpath = properties.getExcelpath();
        String imagepath = properties.getImagepath();
        ExcelUtil.write(sheetName, excelDatas, ExcelData.class, excelpath, imagepath);
        EmailUtil.sendEmail(emailId, nickName, gender, excelpath, sheetName, imagepath);
        return "邮件发送成功！";
    }
}
